package org.kingtop.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 文本请求工具类
 * 
 * @author 陈金波
 * 
 */
public class WebRequestUtil {

	private static final String UNKNOW = "unknown";

	/**
	 * 获取IP地址
	 * 
	 * @return
	 */
	public static String getRemoteIp() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		if (requestAttributes != null) {
			return WebRequestUtil.getRemoteIp(((ServletRequestAttributes) requestAttributes).getRequest());
		}
		return null;
	}

	/**
	 * 获取IP地址
	 * 
	 * @author 陈金波
	 * @param request
	 *            请求
	 * @return ip地址
	 */
	public static String getRemoteIp(HttpServletRequest request) {
		String remoteIp = null;
		if (remoteIp == null || remoteIp.length() == 0) {
			remoteIp = request.getHeader("x-forwarded-for");
			if (remoteIp == null || remoteIp.isEmpty() || UNKNOW.equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getHeader("X-Real-IP");
			}
			if (remoteIp == null || remoteIp.isEmpty() || UNKNOW.equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getHeader("Proxy-Client-IP");
			}
			if (remoteIp == null || remoteIp.isEmpty() || UNKNOW.equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getHeader("WL-Proxy-Client-IP");
			}
			if (remoteIp == null || remoteIp.isEmpty() || UNKNOW.equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getHeader("HTTP_CLIENT_IP");
			}
			if (remoteIp == null || remoteIp.isEmpty() || UNKNOW.equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (remoteIp == null || remoteIp.isEmpty() || UNKNOW.equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getRemoteAddr();
			}
			if (remoteIp == null || remoteIp.isEmpty() || UNKNOW.equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getRemoteHost();
			}
		}
		return remoteIp;
	}

	/**
	 * 是否为指定过滤的客户端发的请求
	 * 
	 * @param request
	 *            求情
	 * @param kaptchaExcludeFilter
	 *            需要过滤的客户端，android : 所有ANDROID设备， mac os：苹果等客户端，windows
	 *            phone:windows系统的手机,:电脑网页客户端
	 * @return true:是指定过滤的客户端，false不是指定过滤的客户端
	 */
	public static boolean isClientFilter(HttpServletRequest request, List<String> kaptchaExcludeFilter) {
		if (request == null || kaptchaExcludeFilter == null || kaptchaExcludeFilter.size() == 0) {
			return false;
		}
		String requestHeader = request.getHeader("user-agent");
		requestHeader = requestHeader.toLowerCase();
		for (int i = 0; i < kaptchaExcludeFilter.size(); i++) {
			if (requestHeader.indexOf(kaptchaExcludeFilter.get(i)) > 0) {
				return true;
			}
		}
		return false;
	}

}
